
package com.novabluetooth.services;

import java.util.Date;

import com.novabluetooth.services.servicedevices.TiWenHtdService;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

/**
 * 初始化服务类
 */
public class BloothTool implements BluetoothInterface{
	private final  String TAG = "BloothTool";

	 BluetoothAdapter mBluetoothAdapter;// ble
	 BluetoothManager mBluetoothManager;
	// private BluetoothAdapter mBluetoothAdapter2;// 蓝牙2.0
	private  Context mContext;
	public  SharedPreferences preferences;
	public  SharedPreferences.Editor editor;
	private  Intent intent = new Intent("com.example.communication.RECEIVER");

	public  final String DEVICE_NAME = "device_name";
	public  final String GET_VALUE = "getValue";
	public  final String TOAST = "toast";
	public  final int MESSAGE_STATE_CHANGE = 1;
	public  final int MESSAGE_READ = 2;
	public  final int MESSAGE_WRITE = 3;
	public  final int MESSAGE_DEVICE_NAME = 4;
	public  final int MESSAGE_TOAST = 5;

	public boolean ifState = false;
	 TJBluetoothLeService mBluetoothLeService;
	 String mDeviceAddress;
	 String mDeviceName;
	 Date date_pre_yyxyj = null;// 鱼跃血压计
	 Date date_pre_krkxy = null;// 科瑞康血氧
	 Date date_pre_htdewq = null;// 和泰达耳温枪
	// Handler mHandler = new Handler();
	 boolean mScanning;
	// Stops scanning after 10 seconds.
	private  final long SCAN_PERIOD = 60000;
	private  boolean isRegisterReceiver = false;
	private  boolean isBound = false;

	/**
	 * 懒汉单例模式
	 * 
	 * @author nova
	 *
	 */
//	private  class LazyHolder {
//		private  final BloothTool INSTANCE = getInstance(mContext);
//	}
//
//	private BloothTool() {
//
//	}

//	public  BloothTool getInstance(Context ctx) {
//		mContext = ctx;
//		Log.w("eeeeeeeeeeeeee----------", "设备服务---开启");
//		preferences = mContext.getSharedPreferences("nova_debug", Context.MODE_PRIVATE);
//		editor = preferences.edit();
//		initView();
//		mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
//		isRegisterReceiver = true;
// 		return LazyHolder.INSTANCE;
//	}
	public   BloothTool(Context ctx) {
		mContext = ctx;
		
		Log.w("eeeeeeeeeeeeee----------", "设备服务---开启");
		preferences = mContext.getSharedPreferences("nova_debug", Context.MODE_PRIVATE);
		editor = preferences.edit();
		initView();
		mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		isRegisterReceiver = true;
//		return LazyHolder.INSTANCE;
	}
	/**
	 * 断开蓝牙连接
	 * 
	 * @author 王婷婷
	 * @date 2017年3月18日 下午5:13:35
	 */
	public void stopBlooth() {
		System.out.print("NoticeService关闭");
		scanLeDevice(false);
		mBluetoothLeService = null;
	}

	/**
	 * 初始化蓝牙信息
	 * 
	 * @author 王婷婷
	 * @date 2015年12月18日 上午10:41:48
	 */
	private  void initView() {
		

		blueState();
		

	}

	/**
	 * 开始扫描
	 * @param enable
	 * @author 王婷婷
	 * @date 2017年7月10日 上午9:48:12
	 */
	public  void scanLeDevice(boolean enable) {
		if (enable) {
			System.out.println("开始检测 ");
			Log.w("noticeservice-----------333----", "正在搜索检测设备");
			mScanning = true;
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			Log.w("noticeservice-----------444----", "sssssssssssss扫描设备失败");
			mScanning = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}



	/**
	 * 蓝牙扫描结果反馈
	 */
	
	// Device scan callback.
	private  BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
			try {
				if (device.getName() != null) {
					Log.e(TAG, device.getName());
					System.out.println("device.getName():" + device.getName() + "\n" + device.getAddress());
					// 判断是否是pad端适配的设备
					if (!isScanDataDevice(device)) {
						return;
					}

					mDeviceName = device.getName();

					Log.e(TAG, mDeviceName);
						// else if (
						// EWEN.equals(mDeviceName)||EWEN2.equals(mDeviceName))
						// {
						// compareDataTime(device,date_pre_htdewq,10);
						// }
				   bindDeviceData(device);


				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	};

	

	private final  ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName componentName, IBinder service) {
			mBluetoothLeService = ((TJBluetoothLeService.LocalBinder) service).getService();
			if (!mBluetoothLeService.initialize()) {
				Log.e("TAG", "Unable to initialize Bluetooth");

				Log.w("noticeservice----------666----", "手机不支持蓝牙");
			}
			// Automatically connects to the device upon successful start-up
			// initialization.
			mBluetoothLeService.connect(mDeviceAddress);
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {
			mBluetoothLeService = null;
		}
	};

	private  IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(TJBluetoothLeService.ACTION_DATA_AVAILABLE);
		return intentFilter;
	}
	/**
	 * 蓝牙连接上之后的返回结果
	 */
	private final  BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				final String action = intent.getAction();
				if (TJBluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
					// mConnected = true;
					updateConnectionState("已连接GATT");
				} else if (TJBluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
					// mConnected = false;
					updateRestartState("断开GATT连接");

				} else if (TJBluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
					// Show all the supported services and characteristics on
					// the
					// user interface.
					// displayGattServices(mBluetoothLeService.getSupportedGattServices());
					updateConnectionState("正在通信");
				} else if (TJBluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
					String data = intent.getStringExtra(TJBluetoothLeService.EXTRA_DATA);
					// TODO 完成对数据的显示
					getResultDevice(data);
					System.out.println("发送数据");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	};

	/**
	 * 更改连接状态
	 * 
	 * @param resourceId
	 * @author 王婷婷
	 * @date 2015年10月19日 下午2:08:29
	 */
	private  void updateConnectionState(final String resourceId) {

		Log.w("noticeservice---------updateConnectionState---", resourceId);

	}

	/**
	 * 更新重启状态
	 * 
	 * @param resourceId
	 * @author 王婷婷
	 * @date 2015年10月19日 下午2:08:16
	 */
	private  void updateRestartState(final String resourceId) {

		// unregisterReceiver(mGattUpdateReceiver);
		if (mServiceConnection != null) {
			mContext.unbindService(mServiceConnection);
		}
		mBluetoothLeService = null;

		Log.w("blooth---------fff----", resourceId + "重新测量");


		scanLeDevice(true);
	}

	public boolean ismScanning() {
		return mScanning;
	}

	public void setmScanning(boolean mScanning) {
		this.mScanning = mScanning;
	}
	/**
	 * 获取结果
	 * @param data
	 * @author 王婷婷
	 * @date 2017年7月10日 上午9:46:38
	 */
		public  void getResultDevice(String data) {

			if (TextUtils.isEmpty(mDeviceName)) {
				return;
			}
			Log.w("noticeservice----------rrrrr----", data);
			Log.w("noticeservice----------deviceName----", "ee" + mDeviceName);
			// 发送Action为com.example.communication.RECEIVER的广播
			intent.putExtra("tj_result", data);
			intent.putExtra("deviceAddress", mDeviceAddress);
			intent.putExtra("deviceName", mDeviceName);
			mContext.sendBroadcast(intent);
		}
		
		/**
		 * 关闭
		 * 
		 * @author 王婷婷
		 * @date 2017年7月10日 上午9:50:01
		 */
		public void closeAndExit() {
			System.out.print("NoticeService关闭");
			scanLeDevice(false);
			try {

				if (isRegisterReceiver) {
					if (mGattUpdateReceiver != null) {
						isRegisterReceiver = false;
						mContext.unregisterReceiver(mGattUpdateReceiver);
					}
				}
				if (isBound) {
					isBound = false;
					if (mServiceConnection != null) {
						mContext.unbindService(mServiceConnection);
					}
				}
				if (mBluetoothLeService != null) {
					mBluetoothLeService.close();
					mBluetoothLeService = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		/**
		 * 绑定数据
		 * @param device
		 * @author 王婷婷
		 * @date 2017年7月10日 上午9:48:38
		 */
		public  void bindDeviceData(BluetoothDevice device) {
			if (mScanning) {
				scanLeDevice(false);
			}

			editor.putString("deviceName", device.getName());
			editor.commit();

			mDeviceAddress = device.getAddress();
			System.out.println(device.getName() + "********************");
			
			if(BluetoothConstant.TIWEN_EWQ_HTD.equals(device.getName())||BluetoothConstant.TIWEN_EWENQ_HTD.equals(device.getName())){
//				Intent gattServiceIntent = new Intent(mContext, TJBluetoothLeService.class);
				Intent gattServiceIntent = new Intent(mContext, TiWenHtdService.class);
				mContext.bindService(gattServiceIntent, mServiceConnection, mContext.BIND_AUTO_CREATE);
				isBound = true;
			}
			
		}
		/**
		 * 判断是否是pad端适配的设备
		 * 
		 * @param device
		 * @return
		 * @author 王婷婷
		 * @date 2017年5月10日 上午9:39:54
		 */
		private  boolean isScanDataDevice(BluetoothDevice device) {
			if (BluetoothConstant.XUEYANG.equals(device.getName()) || BluetoothConstant.XUETANG.equals(device.getName())
					|| BluetoothConstant.TIWEN.equals(device.getName())
					|| BluetoothConstant.TIZHONG.equals(device.getName())
					|| BluetoothConstant.XUEYA.equals(device.getName())  ) {
				return true;
			} else {
				return false;
			}

		}
		/**
		 *没有关机指令的需要判断 比较时间，设置多长时间不能连接
		 * 
		 * @author 王婷婷
		 * @date 2017年6月19日 下午4:39:12
		 */

		private  void compareDataTime(final BluetoothDevice device, Date date_pre, int limitTime) {
			if (date_pre != null) {
				long time_secd = ((new Date()).getTime() - date_pre.getTime()) / 1000;
				Log.w(TAG + "--sec11", String.valueOf(time_secd));
				if (time_secd < limitTime) {
				} else {
					bindDeviceData(device);
				}

			} else {
				bindDeviceData(device);
			}
		}

		@Override
		public void bindDeviceData() {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void blueState() {
			
			
			if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
				Log.e(TAG, "该设备不支持蓝牙4.0");
				Log.w("noticeservice-----------111----", "手机不支持BLE");
				return;
			}

			mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
			mBluetoothAdapter = mBluetoothManager.getAdapter();
			// mBluetoothAdapter2 = BluetoothAdapter.getDefaultAdapter();
			if (mBluetoothAdapter == null) {
				Log.w("noticeservice-----------222----", "手机不支持蓝牙");
				return;
			}
			Log.w("noticeservice-----------tt----", "手机支持蓝牙");
			// 开启蓝牙
			if (!mBluetoothAdapter.isEnabled()) {
				boolean flag = mBluetoothAdapter.enable();
				// 开启蓝牙成功还是失败
				if (flag) {
					Log.e(TAG, "蓝牙开启成功");
					// NovaApplication.isBluetoothOpen = true;
				} else {
					Log.e(TAG, "蓝牙开启失败");
					// NovaApplication.isBluetoothOpen = false;
				}

			} else {
				// NovaApplication.isBluetoothOpen = true;
			}
			
		}
		
}
